var exist = function(board, word) {
    let firstWord = word[0]
    let lenRow = board.length
    let lenCol = board[0].length
    let flag = false
    let cache = {}
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            const item = board[i][j];
            if (item === firstWord) {
                if (flag) {
                    return true
                } else {
                    cache[i + '-' + j] = true
                    search(i, j, 0)
                    cache[i + '-' + j] = false
                }
            }
        }
    }

    function search(row, col, curIndex) {
        if (flag) return
        if (curIndex === word.length - 1 && board[row][col] === word[curIndex]) flag = true
        if (row - 1 >= 0 && row - 1 < lenRow && board[row][col] === word[curIndex] && !cache[(row - 1) + '-' + col]) {
            cache[(row - 1) + '-' + col] = true
            search(row - 1, col, curIndex + 1)
            cache[(row - 1) + '-' + col] = false
        }
        if (row + 1 >= 0 && row + 1 < lenRow && board[row][col] === word[curIndex] && !cache[(row + 1) + '-' + col]) {
            cache[(row + 1) + '-' + col] = true
            search(row + 1, col, curIndex + 1)
            cache[(row + 1) + '-' + col] = false
        }
        if (col - 1 >= 0 && col - 1 < lenCol && board[row][col] === word[curIndex] && !cache[row + '-' + (col - 1)]) {
            cache[row + '-' + (col - 1)] = true
            search(row, col - 1, curIndex + 1)
            cache[row + '-' + (col - 1)] = false
        }
        if (col + 1 >= 0 && col + 1 < lenCol && board[row][col] === word[curIndex] && !cache[row + '-' + (col + 1)]) {
            cache[row + '-' + (col + 1)] = true
            search(row, col + 1, curIndex + 1)
            cache[row + '-' + (col + 1)] = false
        }
    }
    return flag
};
console.log(exist([
        ["C", "A", "A"],
        ["A", "A", "A"],
        ["B", "C", "D"]
    ],
    "AAB"))